
import React, { PureComponent } from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { Breadcrumb, Tabs, Row, Col } from 'antd'
import { FormOutlined } from '@ant-design/icons'
import CustomizeTableProvide, { CustomizeTable, CustomizeTablePagination } from '@common/presentational/CustomizeTable'
import ModifyCardModal from '@components/customer/modal/ModifyCardModal'
import { CUSTOMER_STATUS, CUSTOMER_SEX, INTEGRAL_RECORD_TYPE, BALANCE_RECORD_TYPE } from '@constants/CustomerMember'
import { getHistoryMatchParams } from '@utils/setUrlQuery'
import { priceFenToYuan } from '@utils/priceConversion'
import {
    getCustomerMemberSelection,
    getCustomerMemberDiscount,
    getCustomerConsumptionInfo,
    getCustomerAccountInfo,
    getCustomerOrderList,
    getCustomerBalanceList,
    getCustomerIntegralList,
} from '@sagas/customer'

const mainTabs = {
    summery: {
        tab: '客户概况',
        key: 'summery',
    },
    record: {
        tab: '消费记录',
        key: 'record',
    }
}
const subTabs = {
    order: {
        tab: '订单记录',
        key: 'order',
    },
    balance: {
        tab: '余额变动',
        key: 'balance',
    },
    integral: {
        tab: '积分变动',
        key: 'integral',
    },
}

@withRouter
@connect(() => ({
}), {
    getCustomerMemberSelection,
    getCustomerMemberDiscount,
    getCustomerConsumptionInfo,
    getCustomerAccountInfo,
    getCustomerOrderList,
    getCustomerBalanceList,
    getCustomerIntegralList,
})

class CustomerDetailPage extends PureComponent {
    constructor(props) {
        super(props)
        const { location } = props
        const { id } = getHistoryMatchParams(props)
        const { state = {} } = location
        this.state = {
            id,
            columns: [],
            activeMainTabKey: mainTabs.summery.key,
            activeSubTabKey: subTabs.order.key,
            customerDetail: {
                ...state
            },
            customerConsumptionInfo: {},
            customerAccountInfo: {},
            recordListMap: {},
        }

        this.paginationInfo = { current: 1, pageSize: 20 }

        this.tableRef = React.createRef()
        this.modifyCardModalRef = React.createRef()

        this.handleBack = this.handleBack.bind(this)
        this.handleTabChange = this.handleTabChange.bind(this)
        this.handleSubTabChange = this.handleSubTabChange.bind(this)
        this.handleGetTableInfo = this.handleGetTableInfo.bind(this)
        this.handleModifyCard = this.handleModifyCard.bind(this)
        this.handleGetAccountInfo = this.handleGetAccountInfo.bind(this)
    }

    componentDidMount() {
        const { id: member_id } = this.state
        this.handleTabChange(mainTabs.summery.key)
    }

    _handleGetSummery() {
        const { id: member_id } = this.state
        const { getCustomerConsumptionInfo } = this.props
        getCustomerConsumptionInfo({ member_id }, res => {
            this.setState({
                customerConsumptionInfo: res,
            })
        })
        this.handleGetAccountInfo()
    }

    _handleGetRecord(key) {
        const { id: member_id } = this.state
        const { getCustomerOrderList, getCustomerBalanceList, getCustomerIntegralList } = this.props
        const { current, pageSize } = this.paginationInfo
        let columns = [];
        if (key === subTabs.order.key) {
            columns = [{
                key: 'submit_time',
                dataIndex: 'submit_time',
                title: '时间',
            }, {
                key: 'order_number',
                dataIndex: 'order_number',
                title: '订单编号',
            }, {
                key: 'amount',
                dataIndex: 'amount',
                title: '支付金额',
                render: (text, record) => `${record.amount < 0 ? '-' : ''}¥${priceFenToYuan(Math.abs(record.amount))}`
            }, {
                key: 'refunded_amount',
                dataIndex: 'refunded_amount',
                title: '退款金额',
                render: (text, record) => `${record.refunded_amount < 0 ? '-' : ''}¥${priceFenToYuan(Math.abs(record.refunded_amount))}`
            }]
            this.setState({ columns })
            getCustomerOrderList({
                member_id,
                page_no: current,
                page_size: pageSize,
            }, res => {
                this.setState({
                    recordListMap: res,
                })
            })
        } else if (key === subTabs.balance.key) {
            columns = [{
                key: 'created_at',
                dataIndex: 'created_at',
                title: '时间',
            }, {
                key: 'bal_type',
                dataIndex: 'bal_type',
                title: '类型',
                render: (text, record) => BALANCE_RECORD_TYPE[record.bal_type],
            }, {
                key: 'amount',
                dataIndex: 'amount',
                title: '余额变化',
                render: (text, record) => `${record.amount < 0 ? '-' : ''}¥${priceFenToYuan(Math.abs(record.amount))}`
            }]
            this.setState({ columns })
            getCustomerBalanceList({
                member_id,
                page_no: current,
                page_size: pageSize,
            }, res => {
                this.setState({
                    recordListMap: res,
                })
            })
        } else if (key === subTabs.integral.key) {
            columns = [{
                key: 'created_at',
                dataIndex: 'created_at',
                title: '时间',
            }, {
                key: 'int_type',
                dataIndex: 'int_type',
                title: '类型',
                render: (text, record) => INTEGRAL_RECORD_TYPE[record.int_type],
            }, {
                key: 'num',
                dataIndex: 'num',
                title: '积分变化',
            }]
            this.setState({ columns })
            getCustomerIntegralList({
                member_id,
                page_no: current,
                page_size: pageSize,
            }, res => {
                this.setState({
                    recordListMap: res,
                })
            })
        }
    }

    handleGetAccountInfo() {
        const { id: member_id, customerDetail } = this.state
        const { getCustomerAccountInfo, getCustomerMemberDiscount } = this.props
        customerDetail?.is_formal && getCustomerAccountInfo({ member_id }, res => {
            if (res?.card_id) {
                getCustomerMemberDiscount({
                    card_id: res.card_id,
                }, data => {
                    res.discount = data && data.card_discount ? `${data.card_discount.discount / 10}折` : '- -'
                    this.setState({
                        customerAccountInfo: res,
                    })
                })
            } else {
                this.setState({
                    customerAccountInfo: res,
                })
            }
        })
    }

    handleTabChange(key) {
        this.setState({
            activeMainTabKey: key,
        })
        if (key === mainTabs.summery.key) {
            this._handleGetSummery()
        } else if (key === mainTabs.record.key) {
            this._handleGetRecord(subTabs.order.key)
        }
    }

    handleSubTabChange(key) {
        this.setState({
            activeSubTabKey: key,
        })
        this.paginationInfo = { current: 1, pageSize: 20 }
        this._handleGetRecord(key)
    }

    handleGetTableInfo({ current, pageSize } = this.paginationInfo) {
        this.paginationInfo = { current, pageSize }
        const { activeSubTabKey } = this.state
        this._handleGetRecord(activeSubTabKey)
    }

    handleModifyCard() {
        const { id: member_id, customerAccountInfo } = this.state
        this.props.getCustomerMemberSelection({}, (res) => {
            this.modifyCardModalRef.current?.show({
                cards: res.cards,
                card_id: customerAccountInfo.card_id,
                member_id,
            })
        })
    }

    handleBack() {
        const { history } = this.props
        history.push({
            pathname: `/customer/list`,
        })
    }

    render() {
        const {
            activeMainTabKey,
            activeSubTabKey,
            columns,
            customerDetail,
            customerConsumptionInfo,
            customerAccountInfo,
            recordListMap,
        } = this.state
        return (
            <div className="table-scroll-container customer-detail-page">
                <div className="flex-vertical-center">
                    <Breadcrumb>
                        <Breadcrumb.Item><span className="cur-poi" onClick={this.handleBack}>客户查询</span></Breadcrumb.Item>
                        <Breadcrumb.Item><span>详情</span></Breadcrumb.Item>
                    </Breadcrumb>
                </div>
                <div className="base-panel flex">
                    <div className="avatar">{customerDetail.avatar ? <img src={customerDetail.avatar} /> : null}</div>
                    <div className="mgl-16">
                        <div className="flex mgb-12 ft-16">
                            {customerDetail.nickname}<div className={'status mgl-16 ft-12 ' + customerDetail.status}>{CUSTOMER_STATUS[customerDetail.status]}</div>
                        </div>
                        <div className="flex-vertical-center ft-clr-md">
                            <div className="mgr-36">ID：{customerDetail.member_id || '- -'}</div>
                            <div className="mgr-36">手机号：{customerDetail.mobile || '- -'}</div>
                            <div className="mgr-36">性别：{customerDetail.sex ? CUSTOMER_SEX[customerDetail.sex] : '- -'}</div>
                            <div className="mgr-36">生日：{customerDetail.birthday || '- -'}</div>
                        </div>
                    </div>
                </div>
                <Tabs defaultActiveKey={mainTabs.summery.key} onChange={this.handleTabChange}>
                    <Tabs.TabPane {...mainTabs.summery}>
                        <div className="flex-vertical-center mgb-24 ft-16">消费概况</div>
                        <Row className="stats-panel" gutter={24}>
                            <Col span={6}>
                                <div className="stats-item bg-f5">
                                    <div className="ft-clr-ml mgb-8">最近一次消费</div>
                                    <div className="ft-clr-d ft-32">{customerConsumptionInfo.updated_at || '- -'}</div>
                                </div>
                            </Col>
                            <Col span={6}>
                                <div className="stats-item bg-f5">
                                    <div className="ft-clr-ml mgb-8">累计消费金额</div>
                                    <div className="ft-clr-d ft-32">{customerConsumptionInfo.money_amount ? '￥' + priceFenToYuan(customerConsumptionInfo.money_amount) : '- -'}</div>
                                </div>
                            </Col>
                            <Col span={6}>
                                <div className="stats-item bg-f5">
                                    <div className="ft-clr-ml mgb-8">消费次数</div>
                                    <div className="ft-clr-d ft-32">{customerConsumptionInfo.count || '- -'}</div>
                                </div>
                            </Col>
                            <Col span={6}>
                                <div className="stats-item bg-f5">
                                    <div className="ft-clr-ml mgb-8">客单价</div>
                                    <div className="ft-clr-d ft-32">{customerConsumptionInfo.money_amount ? '￥' + priceFenToYuan(customerConsumptionInfo.money_amount / customerConsumptionInfo.count) : '- -'}</div>
                                </div>
                            </Col>
                        </Row>
                        <div className="flex-vertical-center mgt-24 mgb-24 ft-16">会员卡</div>
                        {customerAccountInfo?.card_id ? <div className="card-panel flex-vertical-center">
                            <div className="card-cover mgb-16 ft-16">
                                <img className="cover-bg" src={customerAccountInfo.cover} />
                                <div className="cover-info flex-vertical-center">
                                    <img className="cover-vip mgr-4" src={require('@assets/image/icon_vip.png')} alt="vip"/>
                                    {customerAccountInfo.card_name}
                                </div>
                            </div>
                            <div className="card-info mgb-16 mgl-24">
                                <div className="ft-16">{customerAccountInfo.card_name}</div>
                                <div className="mgt-16 flex-vertical-center">
                                    <div className="mgr-36">权益：{customerAccountInfo.discount}</div>
                                    <div className="mgr-36">余额：{priceFenToYuan(customerAccountInfo.balance)}元</div>
                                    <div className="mgr-36">积分：{customerAccountInfo.integral}</div>
                                </div>
                                <div className="mgt-16 clr-green ft-12 cur-poi" onClick={this.handleModifyCard}><FormOutlined /> 设置</div>
                            </div>
                        </div> : <div className="ft-16 ft-clr-l">客户未加入会员计划</div>}
                    </Tabs.TabPane>
                    <Tabs.TabPane {...mainTabs.record}>
                        <Tabs className="record-tabs" size="small" defaultActiveKey={subTabs.order.key} onChange={this.handleSubTabChange}>
                            <Tabs.TabPane {...subTabs.order}>
                                {activeSubTabKey === subTabs.order.key ? <CustomizeTableProvide ref={this.tableRef} tableKey={subTabs.order.key} onChange={this.handleGetTableInfo}>
                                    <div className="table-list">
                                        <CustomizeTable
                                            columns={columns}
                                            dataSource={recordListMap.orders || []}
                                        />
                                    </div>
                                    <div className="table-pagination">
                                        <CustomizeTablePagination
                                            total={recordListMap.total}
                                        />
                                    </div>
                                </CustomizeTableProvide> : null }
                            </Tabs.TabPane>
                            <Tabs.TabPane {...subTabs.balance}>
                                {activeSubTabKey === subTabs.balance.key ? <CustomizeTableProvide ref={this.tableRef} tableKey={subTabs.balance.key} onChange={this.handleGetTableInfo}>
                                    <div className="table-list">
                                        <CustomizeTable
                                            columns={columns}
                                            dataSource={recordListMap.balance_logs || []}
                                        />
                                    </div>
                                    <div className="table-pagination">
                                        <CustomizeTablePagination
                                            total={recordListMap.total}
                                        />
                                    </div>
                                </CustomizeTableProvide> : null }
                            </Tabs.TabPane>
                            <Tabs.TabPane {...subTabs.integral}>
                                {activeSubTabKey === subTabs.integral.key ? <CustomizeTableProvide ref={this.tableRef} tableKey={subTabs.integral.key} onChange={this.handleGetTableInfo}>
                                    <div className="table-list">
                                        <CustomizeTable
                                            columns={columns}
                                            dataSource={recordListMap.integrals || []}
                                        />
                                    </div>
                                    <div className="table-pagination">
                                        <CustomizeTablePagination
                                            total={recordListMap.total}
                                        />
                                    </div>
                                </CustomizeTableProvide> : null }
                            </Tabs.TabPane>
                        </Tabs>
                    </Tabs.TabPane>
                </Tabs>
                <ModifyCardModal callback={this.handleGetAccountInfo} ref={this.modifyCardModalRef} />
            </div>
        )
    }
}

export default CustomerDetailPage